#include "widget.h"
#include "ui_widget.h"

#include<QTcpSocket>
#include<QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //修改窗口标题
    this->setWindowTitle("服务器");

    //实例化QUdpsocket对象
    tcpServer = new QTcpServer(this);

    //绑定槽函数，当有新的客户端建立好连接后
    connect(tcpServer,&QTcpServer::newConnection,this,&Widget::processConnection);

    //绑定+监听
    //这和操作得是初始化的最后一步，都是需要把如何处理连接，如何处理请求等都准备好后才能真正绑定端口并监听
    bool ret = tcpServer->listen(QHostAddress::Any,9090);
    if(!ret)
    {
       QMessageBox::critical(this,"服务器启动失败",tcpServer->errorString());
       return;
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    //通过tcpServer拿到一个socket对象，通过这个对象来和客户端进行通信
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    //显示用户上线                      //对端端口号
    QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "]" + "客户端上线了";
    ui->listWidget->addItem(log);

    //如果有数据到达并准备就绪时，通过信号槽来处理客户端发送请求的情况
    connect(clientSocket,&QTcpSocket::readyRead,this,[=](){
        //读取请求数据
        QString req = clientSocket->readAll();

        //根据请求进行响应
        QString resp = process(req);

        //把响应写回客户端
        clientSocket->write(resp.toUtf8());

        //上述操作记录到日志中
        QString log = "[" + clientSocket->peerAddress().toString() + QString::number(clientSocket->peerPort()) + "]"
                + "res:" + req + "resp:" + resp;
        ui->listWidget->addItem(log);
    });

    //当客户端断开时
    connect(clientSocket,&QTcpSocket::disconnected,this,[=](){
        //显示日志
        QString log = "[" + clientSocket->peerAddress().toString() + ":" +QString::number(clientSocket->peerPort()) + "]" + "客户端下线";
        ui->listWidget->addItem(log);

        //手动释放clientSocket
        //在下一轮事件循环在进行销毁操作
        clientSocket->deleteLater();
    });
}

QString Widget::process(const QString req)
{
    return req;
}

